package com.taldh.algorithm.string;

import org.junit.Assert;
import org.junit.Test;

import java.util.Stack;

public class IsValid {

    public char[] left = new char[]{'(','[','{'};
    public char[] right = new char[]{')',']','}'};

    public boolean isValid(String s) {
        if (s == null || s.length() == 0) {
            return true;
        }
        if (s.length() % 2 == 1) {
            return false;
        }
        char[] chars = s.toCharArray();
        Stack<Integer> stack = new Stack<>();
        for (char c : chars) {
            int index = -1;
            if ((index = isLeft(c)) != -1) {
                stack.push(index);
            } else {
                if (stack.isEmpty()) {
                    return false;
                }
                Integer pop = stack.pop();
                if (right[pop] != c) {
                    return false;
                }
            }
        }
        return stack.isEmpty();
    }

    private int isLeft(char c) {
        int count = 0;
        for (char c1 : left) {
            if (c1 == c) {
                return count;
            }
            count += 1;
        }
        return -1;
    }

    @Test
    public void test1() {
        Assert.assertTrue(isValid("()[]{}"));
        Assert.assertTrue(isValid("{[]}"));
    }

    @Test
    public void test2() {
        Assert.assertFalse(isValid("(("));
    }

    @Test
    public void test3() {
        Assert.assertFalse(isValid(")}"));
    }
}